package com.taobao.home.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taobao.base.model.RestResponse;
import com.taobao.home.mapper.ChannelMapper;
import com.taobao.home.model.dto.ChannelDto;
import com.taobao.home.model.po.Channel;
import com.taobao.home.model.po.Goods;
import com.taobao.home.service.CommonService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    // test1
    @Override
    public RestResponse<Goods> test1() {
        List<Goods> goodsList = new ArrayList<>();

        Goods good1 = new Goods();
        good1.setGoodsId(342);
        good1.setTitle("月饼");
        goodsList.add(good1);

        Goods good2 = new Goods();
        good2.setGoodsId(34232);
        good2.setTitle("兔子");
        goodsList.add(good1);
        // 使用RedisTemplate存储列表
        ListOperations<String, Goods> listOps = redisTemplate.opsForList();

        // 将列表转换为数组并存储
        listOps.rightPushAll("goodsList", goodsList.toArray(new Goods[0]));

        // 设置过期时间为5分钟
        redisTemplate.expire("goodsList", 5, TimeUnit.MINUTES);


        return RestResponse.success(good1);
    }

    @Override
    public RestResponse<Goods> test2() {

//        Goods goods = (Goods) redisTemplate.opsForValue().get("goodaa");
        ListOperations<String, Goods> listOps = redisTemplate.opsForList();
        // 获取列表中的所有元素
        List<Goods> goodsList = listOps.range("goodsList", 0, -1);

        return RestResponse.success(goodsList.get(0));
    }

    @Override
    public RestResponse<List<ChannelDto>> getRecommendChannel() {

        QueryWrapper<Channel> queryWrapper = new QueryWrapper<>();

        List<Channel> channelList = channelMapper.selectList(queryWrapper);

        // channelList -> channelDtoList
        List<ChannelDto> channelDtoList = new ArrayList<>();
        for (Channel channel : channelList) {
            ChannelDto channelDto = new ChannelDto();
            // 拷贝
            BeanUtils.copyProperties(channel, channelDto);
            channelDtoList.add(channelDto);
        }

        return RestResponse.success(channelDtoList);
    }
}